<?php
namespace App\Http\Controllers\Mini;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Home\PaymentController;
use App\Models\Addresses;
use App\Models\AdminAgencys;
use App\Models\Buys;
use App\Models\Carts;
use App\Models\Configs;
use App\Models\Goods;
use App\Models\IntegralLogs;
use App\Models\Mails;
use App\Models\OrderGoods;
use App\Models\Orders;
use App\Models\OrderPays;
use App\Models\ProfitLogs;

use App\Models\UserInfos;
use App\Models\Users;

use Illuminate\Http\Request;
use Illuminate\Routing\Route;
use Illuminate\Support\Facades\DB;

class OrdersController extends Controller
{
    protected $_order_data = [];//下单数据

    /**
     * 购买第一步
     * @route api.order.buyStep1
     * @param user_id 用户id
     * @param ifcart 购买类型：0、一步购买 1、购物车购买
     * @param (array)order_info 如果是一步购买：id：商品id，num:购买数量  如果是购物车购买：id:购物车id num:购买数量
     */
    public function buyStep1(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $userinfo = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['nickname','avatar','type','status']);
            if (empty($userinfo)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }else{
                if($userinfo['status'] == 2){
                    return response()->json(["code"=>0, "msg"=>'账户正在审核中，请等待审核!']);
                }elseif($userinfo['status'] == 3){
                    return response()->json(["code"=>0, "msg"=>'账号未通过审核，请前往个人中心查看原因并重新提交审核!']);
                }elseif ($userinfo['status'] == 4){
                    return response()->json(["code"=>0, "msg"=>'账号已锁定，请前往个人中心查看原因或联系客服!']);
                }
                if ($userinfo['type'] != 1) return response()->json(["code"=>0, "msg"=>'供应商不能购买商品!']);
                $more = UserInfos::where('user_id',$user_id)->value('company_name');
                if ($more == null) return response()->json(["code"=>0, "msg"=>'您还未完善信息，请前往个人中心完善信息后再发布!']);
            }

            $ifcart = (int)$request->post('ifcart',0);//0:一步购买 1:购物车购买
            //json转数组
            $orders = json_decode($request->post('order_info'));//商品信息

            foreach ($orders as $k => $v){
                $order_info[] = (array)$this->objectToArray($v);
            }
            //一步购买
            if ($ifcart == 0) {
                //取得POST ID和购买数量
                $buy_items = Buys::parseItems($order_info);
                if (empty($buy_items)) {
                    return response()->json(["code"=>0, "msg"=>'所购商品无效']);
                }
                $goods_id = key($buy_items);
                $buy_num = current($buy_items);

                //商品信息[得到最新商品属性及促销信息]
                $goods_info = Buys::getGoodsOnlineInfo($goods_id, intval($buy_num));
                if (empty($goods_info)) {
                    return response()->json(["code"=>0, "msg"=>'商品已下架或不存在']);
                }
                //进一步处理数组
                $store_cart_list = [];
                $goods_list = [];
                $carts=[];
                $goods_list[0] = $store_cart_list[$goods_info['store_id']]['store_name'] = $goods_info['store_name'];
                $goods_list[1] = $store_cart_list[$goods_info['store_id']]['goods_list'][] = $goods_info;
                foreach ($store_cart_list as $cart){
                    $carts[] = $cart;
                }
                $result =  ['goods_list' => $goods_list, 'store_cart_list' => $carts];
            }elseif ($ifcart == 1) {//购物车购买
                //取得POST ID和购买数量
                $buy_items = Buys::parseItems($order_info);
                if (empty($buy_items)) return response()->json(["code"=>0, "msg"=>'所购商品无效']);
                if (count($buy_items) > 50) return response()->json(["code"=>0, "msg"=>'一次最多只可购买50种商品']);
                //购物车列表
                $params = [
                    'cart_id'=>array_keys($buy_items),
                    'user_id' => $user_id
                ];
                $cart_list = Carts::getCartList($params);
                //购物车列表 [得到最新商品属性]
                $cart_list = Buys::getCartOnlineList($cart_list);
                if (empty($cart_list)) return $cart_list;
                //商品列表
                $goods_list = [];
                $i = 0;
                foreach ($cart_list as $key => $cart) {
                    //购买数量
                    $buy_num = $cart['num'];
                    $goods_list[$i]['goods_num'] = $buy_num;
                    $goods_list[$i]['store_id'] = $cart['store_id'];
                    $goods_list[$i]['store_name'] = $cart['store_name'];
                    $goods_list[$i]['goods_id'] = $cart['goods_id'];
                    $goods_list[$i]['goods_name'] = $cart['goods_name'];
                    $goods_list[$i]['goods_price'] = $cart['goods_price'];
                    $goods_list[$i]['goods_img'] = $cart['goods_img'];
                    $goods_list[$i]['goods_freight'] = $cart['goods_freight'];
                    $goods_list[$i]['goods_type'] = $cart['goods_type'];
                    $i++;
                }
                //以店铺下标归类
                $store_cart_list = [];
                foreach ($cart_list as $cart) {
                    $store_cart_list[$cart['store_id']]['store_name'] = $cart['store_name'];
                    $store_cart_list[$cart['store_id']]['goods_list'][] = $cart;
                }
                $carts=[];
                foreach ($store_cart_list as $cart){
                    $carts[] = $cart;
                }
                $result =  ['goods_list' => $goods_list, 'store_cart_list' => $carts];
            }
            //得到页面所需要数据：收货地址、商品列表等信息
            $lists = [];
            //商品金额计算(分别对每个商品、每个店铺小计)  return [$store_cart_list, $store_goods_total, $store_freight_total,$store_goods_amount];
            list($result['store_cart_list'], $store_goods_total,$store_freight_total,$store_goods_amount) = Buys::calcCartList($result['store_cart_list']);
            $order_goods_total = 0;
            foreach ($store_goods_total as $k=>$v){
                $order_goods_total += $v;
            }

            $lists['store_cart_list'] = $result['store_cart_list'];//以店铺ID分组的购物车商品信息
            $lists['order_goods_total'] = $order_goods_total;//订单总金额
            //输出用户默认收货地址
            $lists['address_info'] = Addresses::details(['user_id'=>$user_id]);

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 购买第二步
     * @route api.order.buyStep2
     * @param user_id 用户id
     * @param ifcart 购买类型： 0、一步购买 1、购物车购买
     * @param address_id 收货地址id
     * @param (array)order_info 如果是一步购买：id：商品id，num:购买数量  如果是购物车购买：id:购物车id num:购买数量
     */
    public function buyStep2(Request $request)
    {
        try {
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $user_info = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','openid','type','status']);
            if (empty($user_info)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }else{
                if($user_info['status'] == 2){
                    return response()->json(["code"=>0, "msg"=>'账户正在审核中，请等待审核!']);
                }elseif($user_info['status'] == 3){
                    return response()->json(["code"=>0, "msg"=>'账号未通过审核，请前往个人中心查看原因并重新提交审核!']);
                }elseif ($user_info['status'] == 4){
                    return response()->json(["code"=>0, "msg"=>'账号已锁定，请前往个人中心查看原因或联系客服!']);
                }
                if ($user_info['type'] != 1) return response()->json(["code"=>0, "msg"=>'供应商不能购买商品!']);
            }

            $ifcart = (int)$request->post('ifcart');
            $address_id = (int)$request->post('address_id');
            //json转数组
            $orders = json_decode($request->post('order_info'));//商品信息
            if (empty($address_id) || empty($orders)){
                return response()->json(["code"=>0, "msg"=>'参数错误']);
            }

            foreach ($orders as $k => $v){
                $cart_info[] = (array)$this->objectToArray($v);
            }

            //取得商品ID和购买数量
            $input_buy_items = Buys::parseItems($cart_info);
            if (empty($input_buy_items)) return response()->json(["code"=>0, "msg"=>'所购商品无效']);
            //验证收货地址
            if ($address_id <= 0) {
                return response()->json(["code"=>0, "msg"=>'请选择收货地址']);
            }else {
                $input_address_info = Addresses::details(['id'=> $address_id]);
                if ($input_address_info['user_id'] != $user_id) {
                    return response()->json(["code"=>0, "msg"=>'请选择收货地址']);
                }
            }

            //保存数据
            $this->_order_data['address_info']  = $input_address_info;//地址信息

            //购物车购买
            if ($ifcart == 1) {
                //购物车列表
                $params = [
                    'cart_id' => array_keys($input_buy_items),
                    'user_id' => $user_id,
                ];
                $cart_list = Carts::getCartList($params);
                //购物车列表 [得到最新商品属性及促销信息]
                $cart_list = Buys::getCartOnlineList($cart_list);
                if (empty($cart_list)) return $cart_list;
                //商品列表
                $goods_list = [];
                $i = 0;
                foreach ($cart_list as $key => $cart) {
                    $buy_num = $cart['num'];//购买数量
                    //商品信息
                    $goods_list[$i]['goods_num'] = $buy_num;
                    $goods_list[$i]['store_id'] = $cart['store_id'];
                    $goods_list[$i]['store_name'] = $cart['store_name'];
                    $goods_list[$i]['goods_id'] = $cart['goods_id'];
                    $goods_list[$i]['goods_name'] = $cart['goods_name'];
                    $goods_list[$i]['goods_price'] = $cart['goods_price'];
                    $goods_list[$i]['goods_img'] = $cart['goods_img'];
                    $goods_list[$i]['goods_freight'] = $cart['goods_freight'];
                    $i++;
                }
                //以店铺下标归类
                $store_cart_list = [];
                foreach ($cart_list as $cart) {
                    $store_cart_list[$cart['store_id']]['store_name'] = $cart['store_name'];
                    $store_cart_list[$cart['store_id']]['goods_list'][] = $cart;
                }
            } else {//来源于直接购买
                $goods_id = key($input_buy_items);
                $buy_num = current($input_buy_items);
                //商品信息[得到最新商品属性及促销信息]
                $goods_info = Buys::getGoodsOnlineInfo($goods_id, intval($buy_num));
                if (empty($goods_info)) {
                    return response()->json(["code"=>0, "msg"=>'商品已下架或不存在']);
                }
                //进一步处理数组
                $store_cart_list = [];
                $goods_list = [];
                $goods_list[0] = $store_cart_list[$goods_info['store_id']]['store_name'] = $goods_info['store_name'];
                $goods_list[0] = $store_cart_list[$goods_info['store_id']]['goods_list'][] = $goods_info;
            }

            //保存数据
            $this->_order_data['store_cart_list'] = $store_cart_list;//已店铺分组的订单详细信息

            //第3步 得到购买相关金额计算等信息
            list($store_cart_list, $store_goods_total,$store_freight_total,$store_goods_amount) = Buys::calcCartList($store_cart_list);//商品金额计算(分别对每个商品、每个店铺小计)

            //判断库存
            $append_premiums_to_cart_list = Buys::appendPremiumsToCartList($store_cart_list);
            if ($append_premiums_to_cart_list === false) {
                return response()->json(["code"=>0, "msg"=>'抱歉，您购买的商品库存不足，请重购买']);
            } else {
                list($store_cart_list, $goods_buy_quantity) = $append_premiums_to_cart_list;
            }
            //计算订单总价
            $pay_amount = 0;
            $pay_freight = 0;
            foreach ($store_goods_total as $order_amount){
                $pay_amount += floatval($order_amount);
            }
            foreach ($store_freight_total as $freight_amount){
                $pay_freight += floatval($freight_amount);
            }

            //保存数据
            $this->_order_data['order_pay_amount']     = $pay_amount;//订单总价
            $this->_order_data['order_freight_amount']     = $pay_freight;//邮费总价
            $this->_order_data['store_cart_list']       = $store_cart_list;//已店铺分组的订单详细信息

            //第4步 生成订单
            extract($this->_order_data);
            $order_list = [];//存储生成的订单数据

            //数据入订单信息表
            $pay_sn = Buys::makePaySn($user_id);
            $order_pay  = [];
            $order_pay['pay_sn'] = $pay_sn;
            $order_pay['user_id'] = $user_id;
            $order_pay_id = OrderPays::create($order_pay);
            if (!$order_pay_id) {
                return response()->json(["code"=>0, "msg"=>'订单保存失败[未生成支付单]']);
            }

            //收货人信息
            $reciver_info = [];
            $reciver_info['realname'] = $input_address_info['realname'];
            $reciver_info['phone'] = $input_address_info['phone'];
            $reciver_info['area'] = $input_address_info['area'];
            $reciver_info['detail'] = $input_address_info['detail'];
            foreach ($store_cart_list as $store_id => $goods_list) {
                $order = [];
                $order_goods = [];
                $numm = null;
                //数据入订单表
                $order['order_sn'] = Buys::makeOrderSn($order_pay_id['id']);
                $order['pay_sn'] = $pay_sn;
                $order['store_id'] = $store_id;
                $order['store_name'] = $goods_list['store_name'];
                $order['user_id'] = $user_id;
                $order['user_name'] = $user_info['username'];
                $order['add_time'] = date('Y-m-d H:i:s');
                $order['order_amount'] = $store_goods_amount[$store_id];
                $order['pay_price'] = $store_goods_total[$store_id];
                $order['shipping_price'] = $store_freight_total[$store_id];
                $order['order_from'] = 2;
                $order['pay_method'] = 1;
                $order['address_id'] = $input_address_info['id'];
                $order['reciver_info'] = serialize($reciver_info);
                foreach ($goods_list['goods_list'] as $kk => $vv){
                    $numm += intval($vv['goods_num']);
                }
                $order['order_number'] = $numm;
                $order_id = Orders::create($order);
                if (!$order_id) {
                    return response()->json(["code"=>0, "msg"=>'订单保存失败[未生成订单数据]']);
                }
                $order['order_id'] = $order_id['id'];
                $order_list[$order_id['id']] = $order;
                //生成order_goods订单商品数据
                $i = 0;
                foreach ($goods_list['goods_list'] as $goods_info) {
                    $order_goods[$i]['order_id'] = $order_id['id'];
                    $order_goods[$i]['store_id'] = $store_id;
                    $order_goods[$i]['user_id'] = $user_id;
                    $order_goods[$i]['goods_id'] = $goods_info['goods_id'];
                    $order_goods[$i]['goods_name'] = $goods_info['goods_name'];
                    $order_goods[$i]['goods_num'] = $goods_info['goods_num'];
                    $order_goods[$i]['goods_image'] = $goods_info['goods_img'];
                    $order_goods[$i]['goods_price'] = $goods_info['goods_price'];
                    $order_goods[$i]['goods_type'] = $goods_info['goods_type'];
                    $order_goods[$i]['created_at'] = date('Y-m-d H:i:s');
                    $order_goods[$i]['updated_at'] = date('Y-m-d H:i:s');
                    $order_goods[$i]['goods_pay_price'] = $goods_info['goods_price'] * $goods_info['goods_num'] + $goods_info['goods_freight'];
                    $i++;
                }
                $insert = OrderGoods::insert($order_goods);
                if (empty($insert)) {
                    return response()->json(["code"=>0, "msg"=>'订单保存失败[未生成商品数据]']);
                }
                $order_list[$order_id['id']]['order_goods']=$order_goods;
            }
            //保存数据
            $this->_order_data['pay_sn'] = $pay_sn;
            $this->_order_data['order_list'] = $order_list;

            //变更库存和销量
            foreach ($goods_buy_quantity as $goods_id => $goods_num) {
                Goods::where('id',$goods_id)->increment('salenum',$goods_num);//销量
                Goods::where('id',$goods_id)->decrement('storage',$goods_num);//库存
            }
            //生成未处理数据给后台
            $maps = [
                'title' => '未处理商品订单',
                'type' => 7,
            ];
            AdminAgencys::create($maps);

            $order_ids = [];
            $order_pays = Orders::where(['pay_sn'=>$pay_sn])->get(['id','user_id','store_name','pay_price']);
            if($ifcart == 1){
                //删除购物车中的商品
                foreach ($input_buy_items as $cart_id => $goods_num) {
                    Carts::where(['id'=>$cart_id,'user_id'=>$user_id])->delete();
                }
            }
            foreach ($order_pays as $key => $val){
                $order_ids[] =  $val['id'];
            }

            $order_num = count($order_ids);
            if($order_num>1){
                $pay_price = 0;
                foreach ($order_pays as $key => $val){
                    $pay_price +=  $val['pay_price'];
                }
                $pay_order = $pay_sn;
                $order_user = $order_pays[0]['user_id'];
            }else{
                $pay_infos = Orders::where(['pay_sn'=>$pay_sn,'id'=>$order_ids[0]])->first(['id','user_id','store_name','pay_price']);
                $new_pay_sn = Buys::makePaySn($pay_infos['user_id']);
                $pay_price = $pay_infos['pay_price'];
                Orders::where(['pay_sn'=>$pay_sn,'id'=>$order_ids[0]])->update(['pay_sn'=>$new_pay_sn]);

                $order_pay = [];
                $order_pay['pay_sn'] = $new_pay_sn;
                $order_pay['user_id'] = $pay_infos['user_id'];
                OrderPays::create($order_pay);

                $pay_order = $new_pay_sn;
                $order_user = $pay_infos['user_id'];
            }

            $detail = '商品支付订单';
            $notify_url = route('home.payment.goodsNotifyUrl');
            $payment = new PaymentController();
            $ret=$payment->wxPayment($pay_order, $order_user, $pay_price,'支付订单',$detail,$notify_url,'JSAPI',$user_info['openid']);

            if($ret['code'] == 1){
                return response()->json(["code"=>1, "msg"=>'获取成功', 'data' => $ret]);
            }else{
                return response()->json(["code"=>0, "msg"=>'获取失败']);
            }
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 订单支付
     * @param url home.order.goodsPayOrder
     * @param user_id 用户id
     * @param order_id 订单id
     * @param pay_order 支付单号
     */
    public function goodsPayOrder(Request $request){
        $user_id = (int)$request->post('user_id');
        if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
        $user_info = Users::where('id',$user_id)->where('status','<>',-1)->first(['username','openid']);
        if (empty($user_info)) return response()->json(["code"=>0, "msg"=>'用户不存在']);

        //根据订单信息，生成支付二维码
        $order_id = $request->post('order_id');//订单id
        if (empty($order_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);

        $order_info = Orders::where(['id'=>$order_id])->first(['id','user_id','store_name','pay_price']);
        $pay_sn = Buys::makePaySn($order_info['user_id']);
        $pay_price = $order_info['pay_price'];
        Orders::where(['id'=>$order_id])->update(['pay_sn'=>$pay_sn]);

        $order_pay = [];
        $order_pay['pay_sn'] = $pay_sn;
        $order_pay['user_id'] = $order_info['user_id'];
        OrderPays::create($order_pay);

        $pay_order = $pay_sn;
        $order_user = $order_info['user_id'];

        $detail = '商品支付订单';
        $notify_url = route('home.payment.goodsNotifyUrl');
        $payment = new PaymentController();
        $ret = $payment->wxPayment($pay_order, $order_user, $pay_price,'支付订单',$detail,$notify_url,'JSAPI',$user_info['openid']);
//        dd($ret);
        if($ret['code'] == 1){
            return response()->json(["code"=>1, "msg"=>'获取成功', 'data' => $ret['data']]);
        }else{
            return response()->json(["code"=>0, "msg"=>'获取失败', 'data' => []]);
        }
    }


    /**
     * 对象转换数组
     * @param $e StdClass对象实例
     * @return array|void
     */
    public function objectToArray($e)
    {
        $e = (array)$e;
        foreach ($e as $k => $v) {
            if (gettype($v) == 'resource') return;
            if (gettype($v) == 'object' || gettype($v) == 'array')
                $e[$k] = (array)$this->objectToArray($v);
        }
        return $e;
    }

}